<?php
/**
 * @package		简易CMS
 * @subpackage	插件函数包
 * @version		$Id: option_portalcp.php 27 2012-09-23 17:39:09Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if (! defined ( 'IN_JYCMS' )) {
	exit ( 'Access Denied' );
}

define ( 'CURSCRIPT', 'portalcp' );
define ( 'NOROBOT', TRUE );
class portalcp_ctrl extends application {
	function __construct() {
		$this->portalcp_ctrl ();
	}
	function portalcp_ctrl() {
		global $_G;
		global $modsession;
		$this->allowaction = array (
				'logout',
				'category',
				'article',
				'related',
				'upload',
				'index',
				'list'
		);

		$this->cachelist = array (
				'portalcategory',
				'customfields'
		);
		parent::__construct ();
		$task = in_array ( $_GET ['task'], array (
				'comment',
				'article',
				'related',
				'block',
				'portalblock',
				'blockdata',
				'diy',
				'upload',
				'category',
				'logout'
		) ) ? $_GET ['task'] : 'index';
		$_G ['gp_task'] = $task;
		if (! $_G ['inajax'] && in_array ( $task, array (
				'index',
				'portalblock',
				'blockdata',
				'category'
		) ) && ($_G ['group'] ['allowmanagearticle'] || $_G ['group'] ['allowauthorizedarticle'] || $_G ['group'] ['allowauthorizedblock'] || $_G ['group'] ['allowdiy'])) {
			require_once libfile ( 'class/panel' );
			$modsession = new ControlPanel ( PORTALCP_PANEL );
			if (getgpc ( 'login_panel' ) && getgpc ( 'cppwd' ) && submitcheck ( 'submit' )) {
				$modsession->dologin ( $_G [uid], getgpc ( 'cppwd' ), true );
			}

			if (! $modsession->islogin) {
				include template ( 'portalcp/login' );
				dexit ();
			}
		}
		require_once libfile ( 'function/portal' );
	}

	/**
	 * 前台管理
	 *
	 * @global array $_G 系统全局变量
	 */
	function onIndex() {
		global $modsession;
		global $_G, $category, $permissioncategory, $navtitle;
		define ( 'CURMODULE', 'portalcp' );

		$navtitle = lang ( 'core', 'Portal management' );

		require_once libfile ( 'function/portalcp' );

		$op = $_GET ['op'] == 'push' ? 'push' : 'list';

		if ($op == 'list' && ! checkperm ( 'allowmanagearticle' ) && ! checkperm ( 'allowauthorizedarticle' )) {
			if (! checkperm ( 'allowdiy' ) && ! checkperm ( 'allowauthorizedblock' )) {
				showmessage ( 'You do not have permission to use the portal management', dreferer () );
			} else {
				dheader ( 'location:index.php?option=block&task=portalblock' );
			}
		}

		$category = $_G ['cache'] ['portalcategory'];
		$permissioncategory = array ();

		if (checkperm ( 'allowmanagearticle' ) || checkperm ( 'allowauthorizedarticle' )) {
			$permissioncategory = $category;
		}

		if ($op == 'push') {

			$categorytree = '';
			foreach ( $permissioncategory as $key => $value ) {
				if ($category [$key] ['level'] == 0) {
					$categorytree .= showcategoryrowpush ( $key, 0 );
				}
			}
		} else {

			$categorytree = '';
			foreach ( $permissioncategory as $key => $value ) {
				if ($category [$key] ['level'] == 0) {
					$categorytree .= showcategoryrow ( $key, 0 );
				}
			}
		}

		include_once template ( "portalcp/index" );
	}
	function onUpload() {
		global $modsession;
		global $_G, $category, $navtitle;
		$operation = $_G ['gp_op'] ? $_G ['gp_op'] : '';
		if ($_G ['gp_formhash'] != formhash ()) {
			portal_upload_error ( lang ( 'system', 'Your request has encountered a problem.' ) );
		}

		require_once libfile ( 'class/upload' );
		$upload = new cmsUpload ();
		$downremotefile = false;
		$attachs = array ();
		$aid = intval ( getgpc ( 'aid' ) );
		if ($operation == 'upload') {
		}
		if (! $_G ['uid']) {
			portal_upload_error ( lang ( 'portalcp', 'Please login first!' ) );
		}
		if ($aid) {
			$query = DB::query ( "SELECT * FROM #__portal_article_title WHERE aid='$aid'" );
			if (! $article = DB::fetch ( $query )) {
				portal_upload_error ( lang ( 'portalcp', 'The article specified does not exist, please check it!' ) );
			}
			if (! $_G ['group'] ['allowmanagearticle'] && (! $_G ['group'] ['allowarticle'] || ($article ['uid'] && $article ['uid'] != $_G ['uid']))) {
				portal_upload_error ( lang ( 'portalcp', 'You do not have permission to operate on the specified article!' ) );
			}
		} else {
			if (! $_G ['group'] ['allowarticle'] && ! $_G ['group'] ['allowmanagearticle']) {
				portal_upload_error ( lang ( 'portalcp', 'You do not have permission to publish the article Operation!' ) );
			}
		}

		if ($operation == 'downremotefile') {
			$arrayimageurl = $temp = $imagereplace = array ();
			$string = stripcslashes ( $_G ['gp_content'] );
			$downremotefile = true;
			$temp = array ();
			preg_match_all ( "/\<img.+src=('|\"|)?(.*)(\\1)([\s].*)?\>/ismUe", $string, $temp, PREG_SET_ORDER );
			if (is_array ( $temp ) && ! empty ( $temp )) {
				foreach ( $temp as $tempvalue ) {
					$tempvalue [2] = str_replace ( '\"', '', $tempvalue [2] );
					if (strlen ( $tempvalue [2] )) {
						$arrayimageurl [] = $tempvalue [2];
					}
				}
				$arrayimageurl = array_unique ( $arrayimageurl );
				if ($arrayimageurl) {
					foreach ( $arrayimageurl as $tempvalue ) {
						$imageurl = $tempvalue;
						$attach ['ext'] = $upload->fileext ( $imageurl );
						if (! $upload->is_image_ext ( $attach ['ext'] )) {
							continue;
						}
						$content = '';
						if (preg_match ( '/^(http:\/\/|\.)/i', $imageurl )) {
							$content = dfsockopen ( $imageurl );
						}
						if (empty ( $content )) {
							continue;
						}
						$imagereplace ['oldimageurl'] [] = $imageurl;
						$temp = explode ( '/', $imageurl );

						$attach ['name'] = trim ( $temp [count ( $temp ) - 1] );
						$attach ['thumb'] = '';

						$attach ['isimage'] = $upload->is_image_ext ( $attach ['ext'] );
						$attach ['extension'] = $upload->get_target_extension ( $attach ['ext'] );
						$attach ['attachdir'] = $upload->get_target_dir ( 'portal' );
						$attach ['attachment'] = $attach ['attachdir'] . $upload->get_target_filename ( 'portal' ) . '.' . $attach ['extension'];
						$attach ['target'] = getglobal ( 'setting/attachdir' ) . './portal/' . $attach ['attachment'];

						if (! @$fp = fopen ( $attach ['target'], 'wb' )) {
							continue;
						} else {
							flock ( $fp, 2 );
							fwrite ( $fp, $content );
							fclose ( $fp );
						}
						if (! $upload->get_image_info ( $attach ['target'] )) {
							@unlink ( $attach ['target'] );
							continue;
						}
						$attach ['size'] = filesize ( $attach ['target'] );
						$attachs [] = daddslashes ( $attach );
					}
				}
			}
		} else {

			$upload->init ( $_FILES ['attach'], 'portal' );
			$attach = $upload->attach;

			if (! $upload->error ()) {
				$upload->save ();
			}
			if ($upload->error ()) {
				portal_upload_error ( $upload->error () );
			}
			$attachs [] = $attach;
		}

		if ($attachs) {

			foreach ( $attachs as $attach ) {
				if ($attach ['isimage']) {
					require_once libfile ( 'class/image' );
					$image = new image ();
					$image->Watermark ( $attach ['target'], '', 'portal' );
					if ($_G ['setting'] ['imgthumb'] == 1) {
						$thumbimgwidth = $_G ['setting'] ['thumbwidth'] ? $_G ['setting'] ['thumbwidth'] : 300;
						$thumbimgheight = $_G ['setting'] ['thumbheight'] ? $_G ['setting'] ['thumbheight'] : 300;
						$attach ['thumb'] = $image->Thumb ( $attach ['target'], '', $thumbimgwidth, $thumbimgheight, 2 );
						// $image->Watermark($attach['target'].'.thumb.jpg', '',
					// 'portal');
					}
				}

				if (getglobal ( 'setting/ftp/on' ) && ((! $_G ['setting'] ['ftp'] ['allowedexts'] && ! $_G ['setting'] ['ftp'] ['disallowedexts']) || ($_G ['setting'] ['ftp'] ['allowedexts'] && in_array ( $attach ['ext'], $_G ['setting'] ['ftp'] ['allowedexts'] )) || ($_G ['setting'] ['ftp'] ['disallowedexts'] && ! in_array ( $attach ['ext'], $_G ['setting'] ['ftp'] ['disallowedexts'] ))) && (! $_G ['setting'] ['ftp'] ['minsize'] || $attach ['size'] >= $_G ['setting'] ['ftp'] ['minsize'] * 1024)) {
					if (ftpcmd ( 'upload', 'portal/' . $attach ['attachment'] ) && (! $attach ['thumb'] || ftpcmd ( 'upload', 'portal/' . $attach ['attachment'] . '.thumb.jpg' ))) {
						@unlink ( $_G ['setting'] ['attachdir'] . '/portal/' . $attach ['attachment'] );
						@unlink ( $_G ['setting'] ['attachdir'] . '/portal/' . $attach ['attachment'] . '.thumb.jpg' );
						$attach ['remote'] = 1;
					} else {
						if (getglobal ( 'setting/ftp/mirror' )) {
							@unlink ( $attach ['target'] );
							@unlink ( $attach ['target'] . '.thumb.jpg' );
							portal_upload_error ( lang ( 'portalcp', 'Remote upload failed!' ) );
						}
					}
				}

				$setarr = array (
						'uid' => $_G ['uid'],
						'filename' => $attach ['name'],
						'attachment' => $attach ['attachment'],
						'filesize' => $attach ['size'],
						'isimage' => $attach ['isimage'],
						'thumb' => $attach ['thumb'],
						'remote' => $attach ['remote'],
						'filetype' => $attach ['extension'],
						'dateline' => $_G ['timestamp'],
						'aid' => $aid
				);
				$setarr ['attachid'] = DB::insert ( "common_attachment", $setarr, true );
				if ($downremotefile) {
					$attach ['url'] = ($attach ['remote'] ? $_G ['setting'] ['ftp'] ['attachurl'] : $_G ['setting'] ['attachurl']) . 'portal/';
					$imagereplace ['newimageurl'] [] = $_G ['siteurl'] . $attach ['url'] . $attach ['attachment'];
				}
				portal_upload_show ( $setarr );
			}
			if ($downremotefile && $imagereplace) {
				$string = preg_replace ( array (
						"/\<(script|style|iframe)[^\>]*?\>.*?\<\/(\\1)\>/si",
						"/\<!*(--|doctype|html|head|meta|link|body)[^\>]*?\>/si"
				), '', $string );
				$string = str_replace ( $imagereplace ['oldimageurl'], $imagereplace ['newimageurl'], $string );
				$string = str_replace ( array (
						"\r",
						"\n",
						"\r\n"
				), '', addcslashes ( $string, '/"\\' ) );
				print "
				<script type='text/javascript'>
					parent.jQuery('#jycms-ttHtmlEditor').val('$string');
				</script>";
			}
			exit ();
		}
	}
	function onRelated() {
		global $modsession;
		global $_G, $category, $navtitle;

		$op = in_array ( $_GET ['op'], array (
				'manual',
				'search',
				'add',
				'get'
		) ) ? $_GET ['op'] : '';
		$aid = intval ( $_G ['gp_aid'] );
		$catid = intval ( $_G ['gp_catid'] );
		if ($aid) {
			check_articleperm ( $catid, $aid );
		} else {
			check_articleperm ( $catid );
		}

		$wherearr = $articlelist = $relatedarr = array ();

		if ($op == 'manual') {
			$manualid = intval ( $_GET ['manualid'] );
			$ra = array ();
			if ($manualid) {
				$query = DB::query ( "SELECT * FROM #__portal_article_title WHERE aid='$manualid' limit 0, 20" );
				$ra = DB::fetch ( $query );
			}
		} elseif ($op == 'get') {
			$id = trim ( $_GET ['id'] );
			$getidarr = explode ( ',', $id );
			$getidarr = array_map ( 'intval', $getidarr );
			$getidarr = array_unique ( $getidarr );
			$getidarr = array_filter ( $getidarr );
			if ($getidarr) {
				$query = DB::query ( "SELECT * FROM #__portal_article_title WHERE aid IN (" . dimplode ( $getidarr ) . ") limit 0, 20" );
				$list = array ();
				while ( ($value = DB::fetch ( $query )) ) {
					$list [$value ['aid']] = $value;
				}
				foreach ( $getidarr as $getid ) {
					if ($list [$getid]) {
						$articlelist [] = $list [$getid];
					}
				}
			}
		} elseif ($op == 'search') {

			$catids = array ();
			$searchkey = stripsearchkey ( $_GET ['searchkey'] );
			$searchcate = intval ( $_GET ['searchcate'] );
			$catids = category_get_childids ( 'portal', $searchcate );
			$catids [] = $searchcate;
			if ($searchkey) {
				$wherearr [] = "title LIKE '%$searchkey%'";
			}
			$searchcate = dhtmlspecialchars ( $searchcate );
			if ($searchcate) {
				$wherearr [] = "catid IN  (" . dimplode ( $catids ) . ")";
			}
			$wheresql = implode ( ' AND ', $wherearr );
			if ($wheresql) {
				$wheresql = " WHERE " . $wheresql;
			}
			$count = DB::result ( DB::query ( "SELECT COUNT(*) FROM #__portal_article_title$wheresql" ), 0 );
			if ($count) {
				$query = DB::query ( "SELECT * FROM #__portal_article_title$wheresql ORDER BY dateline DESC limit 0, 20" );
				while ( $value = DB::fetch ( $query ) ) {
					$articlelist [] = $value;
				}
			}
		} elseif ($op == 'add') {
			$relatedid = trim ( $_GET ['relatedid'] );
			$relatedarr = explode ( ',', $relatedid );
			$relatedarr = array_map ( 'intval', $relatedarr );
			$relatedarr = array_unique ( $relatedarr );
			$relatedarr = array_filter ( $relatedarr );
			if ($relatedarr) {
				$query = DB::query ( "SELECT * FROM #__portal_article_title WHERE aid IN (" . dimplode ( $relatedarr ) . ")" );
				$list = array ();
				while ( ($value = DB::fetch ( $query )) ) {
					$list [$value ['aid']] = $value;
				}
				foreach ( $relatedarr as $relateid ) {
					if ($list [$relateid]) {
						$articlelist [] = $list [$relateid];
					}
				}
			}
		} else {
			$count = DB::result ( DB::query ( "SELECT COUNT(*) FROM #__portal_article_title" ), 0 );
			if ($count) {
				$query = DB::query ( "SELECT * FROM #__portal_article_title ORDER BY dateline DESC limit 0, 20" );
				while ( $value = DB::fetch ( $query ) ) {
					$articlelist [] = $value;
				}
			}
		}
		$category = category_showselect ( 'portal', 'searchcate', false, $_G [gp_searchcate] );
		include_once template ( "portalcp/related_article" );
	}
	function onArticle() {
		global $modsession;
		global $_G, $category, $navtitle;
		$op = in_array ( $_GET ['op'], array (
				'addpage',
				'edit',
				'delpage',
				'delete',
				'related',
				'batch',
				'verify'
		) ) ? $_GET ['op'] : 'add';
		$aid = intval ( $_G ['gp_aid'] );
		$catid = intval ( $_G ['gp_catid'] );
		loadcache ( 'customfields' );
		$customfields = $_G ['cache'] ['customfields'];
		$article = $article_content = array ();
		if ($aid) {
			$article = DB::fetch_first ( "SELECT * FROM #__portal_article_title WHERE aid='$aid'" );
			if (! $article) {
				showmessage ( 'Article is not exist!', dreferer () );
			}
			DB::query ( "SELECT a.*, b.tagname FROM #__common_tags a LEFT JOIN #__common_tagslist b on b.tagid=a.tagid WHERE a.itemid='$aid' AND a.tagtype='portal'" );
			$tags = DB::fetch_all ();
			if ($tags) {
				$article ['tagname'] = array ();
				foreach ( ( array ) $tags as $v )
					$article ['tagname'] [] = $v ['tagname'];
				$article ['tagname'] = implode ( ',', $article ['tagname'] );
			}
		}
		$cat = array ();
		if ($catid)
			$cat = category_remake ( $catid );

		loadcache ( 'portalcategory' );
		$portalcategory = $_G ['cache'] ['portalcategory'];
		if ($catid && empty ( $portalcategory [$catid] )) {
			showmessage ( 'Did not find the specified category!', dreferer () );
		}
		if (empty ( $article ) && $catid && $portalcategory [$catid] ['disallowpublish']) {
			showmessage ( 'Articles in this category do not allow!', dreferer () );
		}

		if (submitcheck ( "articlesubmit", 0 )) {

			if ($aid) {
				check_articleperm ( $article ['catid'], $aid );
			} else {
				check_articleperm ( $catid );
			}
			$customfieldid = intval ( $_G ['gp_customfieldid'] );
			if ($customfieldid) {
				$customfieldtext = serialize ( $_G ['gp_customfieldtext'] [$customfieldid] );
			}
			$_POST ['title'] = getstr ( trim ( $_POST ['title'] ), 80, 1, 1 );
			if (strlen ( $_POST ['title'] ) < 1) {
				showmessage ( 'Title can not be less than 2 characters!' );
			}
			$_POST ['title'] = censor ( $_POST ['title'] );
			if (!$_G['gp_shorttitle']){
				if(!$_G['ch']) {
					require_once libfile('class/chinese');
				}
				$_G['ch'] = new Chinese('UTF-8', 'PINYIN');
				$_G['gp_shorttitle'] = $_G['ch']->Convert($_POST['title']);
			}
			//$_G['gp_shorttitle'] = getstr(trim(dhtmlspecialchars($_G['gp_shorttitle'])), 80, 1, 1);

			if (empty ( $_POST ['summary'] ))
				$_POST ['summary'] = preg_replace ( "/(\s|###NextPage###)+/", ' ', $_POST ['content'] );
			$summary = portalcp_get_summary ( stripslashes ( $_POST ['summary'] ) );
			$summary = censor ( $summary );

			$_G ['gp_author'] = dhtmlspecialchars ( $_G ['gp_author'] );
			$_G ['gp_url'] = str_replace ( '&amp;', '&', dhtmlspecialchars ( $_G ['gp_url'] ) );
			$_G ['gp_from'] = dhtmlspecialchars ( $_G ['gp_from'] );
			$_G ['gp_fromurl'] = str_replace ( '&amp;', '&', dhtmlspecialchars ( $_G ['gp_fromurl'] ) );
			if (censormod ( $_POST ['title'] ) || $_G ['group'] ['allowarticlemod']) {
				$article_status = 1;
			} else {
				$article_status = 0;
			}
			// TAG处理
			if (empty ( $_POST ['tagname'] ))
				$_POST ['tagname'] = '';
			$tagarr = posttag ( $_POST ['tagname'] );

			$setarr = array (
					'title' => $_POST ['title'],
					'shorttitle' => $_G['gp_shorttitle'],
					'author' => $_G ['gp_author'],
					'from' => $_G ['gp_from'],
					'fromurl' => $_G ['gp_fromurl'],
					'url' => $_G ['gp_url'],
					'allowcomment' => ! empty ( $_POST ['forbidcomment'] ) ? '0' : '1',
					'summary' => addslashes ( $summary ),
					'catid' => intval ( $_POST ['catid'] ),
					'status' => $article_status,
					'customfieldid' => $customfieldid,
					'customfieldtext' => $customfieldtext,
					'readed' => 3
			);
			if (! $aid) {
				$setarr ['dateline'] = $_G ['timestamp'];
			}
			if (empty ( $setarr ['catid'] )) {
				showmessage ( 'Please select an appropriate system of classification!' );
			}

			if ($_G ['gp_conver']) {
				$converfiles = unserialize ( stripcslashes ( $_G ['gp_conver'] ) );
				$setarr ['pic'] = $converfiles ['pic'];
				$setarr ['thumb'] = $converfiles ['thumb'];
				$setarr ['remote'] = $converfiles ['remote'];
			}
			if (empty ( $article )) {
				$setarr ['uid'] = $_G ['uid'];
				$setarr ['username'] = $_G ['username'];
				$table = '';
				$aid = DB::insert ( 'portal_article_title', $setarr, 1 );
				updatecreditbyaction ( 'postarticle', $_G ['uid'] );
				// 信息与tag关联处理
				postspacetag ( 'add', 'portal', $aid, $tagarr );
				DB::update ( 'common_member', array (
						'lastpost' => $_G ['timestamp']
				), array (
						'uid' => $_G ['uid']
				) );
				DB::query ( "UPDATE #__common_category SET articles=articles+1 WHERE catid = '$setarr[catid]'" );
			} else {
				// 信息与tag关联处理
				postspacetag ( 'update', 'portal', $aid, $tagarr );
				DB::update ( 'portal_article_title', $setarr, array (
						'aid' => $aid
				) );
			}

			$cid = intval ( $_POST ['cid'] );
			if ($cid) {
				$query = DB::query ( "SELECT * FROM #__portal_article_content WHERE cid='$cid' AND aid='$aid'" );
				$article_content = DB::fetch ( $query );
			}

			$content = getstr ( $_POST ['content'], 0, 1, 1, 0, 1 );
			$content = censor ( $content );
			if (censormod ( $content ) || $_G ['group'] ['allowarticlemod']) {
				$article_status = 1;
			} else {
				$article_status = 0;
			}
			$contents = explode ( '###NextPage###', $content );
			$content_count = count ( $contents );

			$pageorder = intval ( $_POST ['pageorder'] );

			if ($pageorder > 0) {
				$startorder = $pageorder - 1;
				$pageorder = DB::result ( DB::query ( "SELECT pageorder FROM #__portal_article_content WHERE aid='$aid' ORDER BY pageorder LIMIT $startorder, 1" ), 0 );

				if ($article_content && $article_content ['pageorder'] == $pageorder) {
					$content_count = $content_count - 1;
				}
				if ($content_count > 0) {
					DB::query ( "UPDATE #__portal_article_content SET pageorder = pageorder+$content_count WHERE aid='$aid' AND pageorder>='$pageorder'" );
				}
			} else {
				$pageorder = DB::result ( DB::query ( "SELECT MAX(pageorder) FROM #__portal_article_content WHERE aid='$aid'" ), 0 );
				$pageorder = $pageorder + 1;
			}

			if ($article_content) {
				$setarr = array (
						'content' => trim ( $contents [0] ),
						'pageorder' => $pageorder,
						'dateline' => $_G ['timestamp']
				);
				DB::update ( 'portal_article_content', $setarr, array (
						'cid' => $cid
				) );
				if (censormod ( $contents [0] )) {
					DB::update ( 'portal_article_title', array (
							'status' => 1
					), array (
							'aid' => $aid
					) );
				}
				unset ( $contents [0] );
			}

			if ($contents) {
				$inserts = array ();
				foreach ( $contents as $key => $value ) {
					$value = trim ( $value );
					$inserts [] = "('$aid', '$value', '" . ($pageorder + $key) . "', '$_G[timestamp]')";
				}
				DB::query ( "INSERT INTO #__portal_article_content
					(aid, content, pageorder, dateline)
					VALUES " . implode ( ',', $inserts ) );

				DB::query ( "UPDATE #__portal_article_title SET status = '$article_status', contents = contents+" . count ( $inserts ) . " WHERE aid='$aid'" );
			}

			$newaids = array ();
			$_POST ['attach_ids'] = explode ( ',', $_POST ['attach_ids'] );
			foreach ( $_POST ['attach_ids'] as $newaid ) {
				$newaid = intval ( $newaid );
				if ($newaid)
					$newaids [$newaid] = $newaid;
			}
			if ($newaids) {
				DB::update ( 'common_attachment', array (
						'aid' => $aid
				), "attachid IN (" . dimplode ( $newaids ) . ") AND aid='0'" );
			}

			DB::query ( "DELETE FROM #__portal_article_related WHERE aid='$aid' OR raid='$aid'" );
			if ($_POST ['raids']) {
				$relatedarr = array ();
				$relatedarr = array_map ( 'intval', $_POST ['raids'] );
				$relatedarr = array_unique ( $relatedarr );
				$relatedarr = array_filter ( $relatedarr );
				if ($relatedarr) {
					$query = DB::query ( "SELECT * FROM #__portal_article_title WHERE aid IN (" . dimplode ( $relatedarr ) . ")" );
					$list = array ();
					while ( ($value = DB::fetch ( $query )) ) {
						$list [$value ['aid']] = $value;
					}
					$replaces = array ();
					$displayorder = 0;
					foreach ( $relatedarr as $relate ) {
						if (($value = $list [$relate])) {
							if ($value ['aid'] != $aid) {
								$replaces [] = "('$aid', '$value[aid]', '$displayorder')";
								$replaces [] = "('$value[aid]', '$aid', '0')";
								$displayorder ++;
							}
						}
					}
					if ($replaces) {
						DB::query ( "REPLACE INTO #__portal_article_related (aid,raid,displayorder) VALUES " . implode ( ',', $replaces ) );
					}
				}
			}

			if ($_POST ['addpage']) {
				$url = 'index.php?option=portalcp&task=article&op=addpage&aid=' . $aid;
			} else {
				$url = $_POST ['url'] ? "index.php?task=list&catid=$_POST[catid]" : 'index.php?task=view&aid=' . $aid;
			}
			showmessage ( 'The operation completed!', $url );
		} elseif (submitcheck ( 'verifysubmit' )) {
			if ($aid) {
				check_articleperm ( $article ['catid'], $aid, true );
			} else {
				showmessage ( 'Article is not exist!', dreferer () );
			}
			if ($_POST ['status'] == '0') {
				DB::update ( 'portal_article_title', array (
						'status' => '0'
				), array (
						'aid' => $aid
				) );

				$tourl = dreferer ( 'index.php?task=view&aid=' . $aid );
				showmessage ( 'Articles have been approved!', $tourl );
			} elseif ($_POST ['status'] == '2') {
				DB::update ( 'portal_article_title', array (
						'status' => '2'
				), array (
						'aid' => $aid
				) );

				$tourl = dreferer ( 'index.php?task=view&aid=' . $aid );
				showmessage ( 'Articles have been ignored!', $tourl );
			} elseif ($_POST ['status'] == '-1') {
				include_once libfile ( 'function/delete' );
				deletearticle ( array (
						$aid
				), 0 );

				$tourl = dreferer ( 'index.php?option=portalcp&task=category&catid=' . $article ['catid'] );
				showmessage ( 'Articles have been deleted!', $tourl );
			} else {
				showmessage ( 'Please select the operating items!' );
			}
		}

		if ($op == 'delpage') {

			if (! $aid) {
				showmessage ( 'You do not have permission to operate the current article!' );
			}
			check_articleperm ( $article ['catid'], $aid );

			$pageorder = intval ( $_GET ['pageorder'] );
			$aid = intval ( $_GET ['aid'] );
			$cid = intval ( $_GET ['cid'] );

			if ($aid && $cid) {
				$count = DB::result ( DB::query ( "SELECT COUNT(*) FROM #__portal_article_content WHERE aid='$aid'" ), 0 );
				if ($count > 1) {
					DB::query ( "DELETE FROM #__portal_article_content WHERE cid='$cid' AND aid='$aid'" );
					DB::query ( "UPDATE #__portal_article_title SET contents = contents-1 WHERE aid='$aid'" );
				} else {
					showmessage ( 'Current as the last page can not be deleted, please return!' );
				}
			}
			showmessage ( 'The operation completed!', "index.php?option=portalcp&task=article&op=edit&quickforward=1&aid=$aid" );
		} elseif ($op == 'delete') {

			if (! $aid) {
				showmessage ( 'You do not have permission to operate the current article!' );
			}
			check_articleperm ( $article ['catid'], $aid );

			if (submitcheck ( 'deletesubmit' )) {
				include_once libfile ( 'function/delete' );
				$article = deletearticle ( array (
						intval ( $_POST ['aid'] )
				), intval ( $_POST ['optype'] ) );
				showmessage ( 'Completion of the specified article deleted', "index.php?task=list&catid={$article[0][catid]}" );
			}
		} elseif ($op == 'related') {

			$raid = intval ( $_GET ['raid'] );
			$ra = array ();
			if ($raid) {
				$query = DB::query ( "SELECT * FROM #__portal_article_title WHERE aid='$raid'" );
				$ra = DB::fetch ( $query );
			}
		} elseif ($op == 'batch') {

			check_articleperm ( $catid );

			$aids = $_POST ['aids'];
			$optype = $_POST ['optype'];
			if (empty ( $optype ) || $optype == 'push')
				showmessage ( 'Please select the operation to be carried out' );
			if (empty ( $aids ))
				showmessage ( 'Please choose an article to be operated!' );

			if (submitcheck ( 'batchsubmit' )) {
				if ($optype == 'trash' || $optype == 'delete') {
					require_once libfile ( 'function/delete' );
					$istrash = $optype == 'trash' ? 1 : 0;
					$article = deletearticle ( $_POST ['aids'], $istrash );
					showmessage ( 'Completion of the specified article deleted', dreferer ( "index.php?option=portalcp&task=category&catid={$article[0][catid]}" ) );
				}
			}
		} elseif ($op == 'verify') {
			if ($aid) {
				check_articleperm ( $article ['catid'], $aid );
			} else {
				showmessage ( 'Article is not exist!', dreferer () );
			}
		} else {

			if ($aid) {
				$catid = intval ( $article ['catid'] );
			}
			check_articleperm ( $catid, $aid );

			$page = empty ( $_GET ['page'] ) ? 1 : intval ( $_GET ['page'] );
			if ($page < 1)
				$page = 1;
			$start = $page - 1;

			$pageselect = '';

			require_once libfile ( 'function/portalcp' );
			$category = $_G ['cache'] ['portalcategory'];
			$cate = $category [$catid];

			if ($article) {
				if ($op == 'addpage') {
					$article_content = array ();
				} else {
					$query = DB::query ( "SELECT * FROM #__portal_article_content WHERE aid='$aid' ORDER BY pageorder LIMIT $start,1" );
					$article_content = DB::fetch ( $query );
				}
				// @todo 不知道为什么代码总是被直接转化出来，郁闷！
				if (isset ( $article_content ['content'] )) {
					$article_content ['content'] = htmlentities ( $article_content ['content'], ENT_COMPAT, 'utf-8' );
				}
				$article ['attach_image'] = $article ['attach_file'] = '';
				$query = DB::query ( "SELECT * FROM #__common_attachment WHERE aid='$aid' ORDER BY attachid" );
				while ( $value = DB::fetch ( $query ) ) {
					if ($value ['isimage']) {
						if ($article ['pic']) {
							$value ['pic'] = $article ['pic'];
						}
						$article ['attach_image'] .= get_uploadcontent ( $value );
					} else {
						$article ['attach_file'] .= get_uploadcontent ( $value );
					}
				}
				if ($article ['contents'] > 0) {
					$pageselect = '<select name="pageorder">';
					$pageselect .= "<option value=\"0\">" . lang ( 'core', 'End' ) . "</option>";
					for($i = 1; $i <= $article ['contents']; $i ++) {
						$selected = ($op != 'addpage' && $page == $i) ? ' selected' : '';
						$pageselect .= "<option value=\"$i\"$selected>$i</option>";
					}
					$pageselect .= '</select>';
				}

				$multi = multi ( $article ['contents'], 1, $page, "index.php?option=portalcp&task=article&aid=$aid", 0, 5 );

				$article ['related'] = array ();
				if ($page < 2 && $op != 'addpage') {
					$query = DB::query ( "SELECT a.aid,a.title
						FROM #__portal_article_related r
						LEFT JOIN #__portal_article_title a ON a.aid=r.raid
						WHERE r.aid='$aid' ORDER BY r.displayorder" );
					while ( $value = DB::fetch ( $query ) ) {
						$article ['related'] [] = $value;
					}
				}
			}
			$cfhtml = '';
			$tbodynum = 0;
			if ($customfields)
				foreach ( $customfields as $cfkey => $cfvalue ) {
					if (empty ( $article ['customfieldid'] )) {
						if ($cfvalue ['isdefault']) {
							$article ['customfieldid'] = $cfvalue ['customfieldid'];
						}
					}
					$cfhtmlselect [$cfvalue ['customfieldid']] = $cfvalue ['name'];
					$cfarr = $cfvalue ['customfieldtext'];
					if (is_array ( $cfarr ) && $cfarr) {
						if (! empty ( $article ['customfieldid'] ) && $article ['customfieldid'] == $cfvalue ['customfieldid']) {
							$tbodydisplay = '';
							if (empty ( $article ['customfieldtext'] )) {
								$thecfarr = array ();
							} else {
								$thecfarr = unserialize ( $article ['customfieldtext'] );
							}
						} else {
							$tbodydisplay = 'none';
							$thecfarr = array ();
						}
						$tbodynum ++;
						$cfhtml .= '<div id="cf_' . $tbodynum . '" class="customfield clearfix" style="display:' . $tbodydisplay . ';">';
						foreach ( $cfarr as $ckey => $cvalue ) {
							$inputstr = '';
							if (empty ( $thecfarr [$ckey] ))
								$thecfarr [$ckey] = '';
							$cfoptionarr = array ();
							if ($cvalue ['type'] == 'select' || $cvalue ['type'] == 'checkbox') {
								$cfoptionarr = processOptions ( $cvalue ['option'] );
							}
							switch ($cvalue ['type']) {
								case 'input' :
								case 'url' :
									$inputstr = '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']" type="text" size="80" value="' . $thecfarr [$ckey] . '" class="px" />';
									break;
								case 'select' :
									$inputstr = '<select name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']"';
									$inputstr .= '>' . "\n";
									foreach ( $cfoptionarr as $tmpkey => $tmpvalue ) {
										if (is_string($thecfarr[$ckey]) && strlen ( $thecfarr [$ckey] ) > 0 && $tmpkey == $thecfarr [$ckey]) {
											$tmpselected = ' selected';
										} else {
											$tmpselected = '';
										}
										$inputstr .= '<option value="' . $tmpkey . '"' . $tmpselected . '>' . $tmpvalue . '</option>' . "\n";
									}
									$inputstr .= '</select>';
									break;

								case 'urls' :
									$str = '<div id="addurls_' . $cfvalue ['customfieldid'] . '_' . $ckey . '" style="border: 1px solid #ccc;clear:both;">';
									if ($thecfarr [$ckey] ['url'] && is_array ( $thecfarr [$ckey] ['url'] )) {
										$notes = $thecfarr [$ckey] ['note'];
										$urls = $thecfarr [$ckey] ['url'];
										foreach ( $urls as $k => $v ) {
											$str .= $this->lang->_ ( 'Description' ) . '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][note][]" type="text" size="80" value="' . $notes [$k] . '" class="px" style="margin: 4px 0" /><br />';
											$str .= $this->lang->_ ( 'Download URL' ) . '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][url][]" type="text" size="80" value="' . $v . '" class="px" style="margin: 4px 0" /><br />';
										}
									} else {
										$str .= $this->lang->_ ( 'Description' ) . '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][note][]" type="text" size="80" value="" class="px" style="margin: 4px 0" /><br />';
										$str .= $this->lang->_ ( 'Download URL' ) . '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][url][]" type="text" size="80" value="" class="px" style="margin: 4px 0" /><br />';
									}
									$strx = '';
									$strx .= $this->lang->_ ( 'Description' ) . "<input name=\\'customfieldtext[" . $cfvalue ['customfieldid'] . "][$ckey][note][]\\' type=\\'text\\' size=\\'80\\' value=\\'\\' class=\\'px\\' style=\\'margin: 4px 0\\' /><br />";
									$strx .= $this->lang->_ ( 'Download URL' ) . "<input name=\\'customfieldtext[" . $cfvalue ['customfieldid'] . "][$ckey][url][]\\' type=\\'text\\' size=\\'80\\' value=\\'\\' class=\\'px\\' style=\\'margin: 4px 0\\' /><br />";
									$inputstr = $str . '</div><input type="button" class="btn" value="' . $this->lang->_ ( 'Add' ) . '" onclick="adddivcustomfield(\'addurls_' . $cfvalue ['customfieldid'] . '_' . $ckey . '\', \'' . $strx . '\');" />';
									break;
								case 'input' :
								case 'url' :
									$inputstr = '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']" type="text" size="80" value="' . $thecfarr [$ckey] . '" class="px" />';
									break;
								case 'textarea' :
									$inputstr = '<textarea name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']" rows="5" cols="60">' . $thecfarr [$ckey] . '</textarea>';
									break;
							}
							$cfhtml .= '<dl><dt>' . $cvalue ['name'] . '</dt><dd>' . $inputstr . '</dd></dl>';
						}
						$cfhtml .= '</div>';
					}
				}
			$cfhtml = str_replace ( '</div></div>', '</div>', $cfhtml );
			if (! empty ( $article ['dateline'] )) {
				$article ['dateline'] = dgmdate ( $article ['dateline'] );
			}
		}

		$allcategory = getcattree ();
		if (! $allcategory) {
			showmessage ( 'Classification not yet been established!', dreferer () );
		}
		$authcode = authcode ( $_G ['member'] ['password'] . "\t" . $_G ['uid'], 'ENCODE' );
		include_once template ( "portalcp/article" );
	}
	function onCategory() {
		global $modsession;
		global $_G, $category, $navtitle;
		require_once libfile ( 'function/portalcp' );
		$catid = max ( 0, intval ( $_GET ['catid'] ) );
		if (! checkperm ( 'allowmanagearticle' )) {
			showmessage ( 'You do not have permission to use the portal management' );
		}
		$category = $_G ['cache'] ['portalcategory'];
		$cate = $category [$catid];
		if (empty ( $cate )) {
			showmessage ( 'Category can not be empty!' );
		}
		$cat = array ();
		if ($catid)
			$cat = category_remake ( $catid );
		$allowmanage = checkperm ( 'allowmanagearticle' ) ? true : false;
		$allowpublish = checkperm ( 'allowmanagearticle' ) ? true : false;
		$wherearr = array ();
		$catids = category_get_childids ( 'portal', $catid );
		$catids [] = $catid;
		$wherearr [] = "catid IN (" . dimplode ( $catids ) . ")";
		if ($_GET ['searchkey']) {
			$_GET ['searchkey'] = stripsearchkey ( $_GET ['searchkey'] );
			$wherearr [] = "title LIKE '%$_GET[searchkey]%'";
		}
		$wheresql = implode ( ' AND ', $wherearr );
		$perpage = 15;
		$page = max ( 1, intval ( $_GET ['page'] ) );
		$start = ($page - 1) * $perpage;
		if ($start < 0)
			$start = 0;
		$list = array ();
		$multi = '';
		$count = DB::result ( DB::query ( "SELECT COUNT(*) FROM #__portal_article_title WHERE $wheresql" ), 0 );
		if ($count) {
			$query = DB::query ( "SELECT * FROM #__portal_article_title WHERE $wheresql ORDER BY dateline DESC LIMIT $start,$perpage" );
			while ( $value = DB::fetch ( $query ) ) {
				if ($value ['pic'])
					$value ['pic'] = pic_get ( $value ['pic'], 'portal', $value ['thumb'], $value ['remote'] );
				$value ['dateline'] = dgmdate ( $value ['dateline'] );
				$value ['allowmanage'] = $allowmanage;
				$value ['allowpublish'] = $allowpublish;
				$list [] = $value;
			}
			$multi = multi ( $count, $perpage, $page, "index.php?option=portalcp&task=category&catid=$catid" );
		}
		include_once template ( "portalcp/category" );
	}
	function onLogout() {
		require_once libfile ( 'class/panel' );
		$modsession = new ControlPanel ( PORTALCP_PANEL );
		$modsession->dologout ();
		showmessage ( 'Successful exit management panel to return to site!', 'index.php' );
	}
}
